package com.ruicar.afs.cloud.workflow.greatwall.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.workflow.greatwall.entity.AfsGreatWallFlowParams;
import com.ruicar.afs.cloud.workflow.greatwall.service.AfsGreatWallFlowParamsService;
import com.ruicar.afs.cloud.workflow.greatwall.vo.FlowParamVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/workFlowParamConfig")
public class AfsGreatWallWorkFLowParamConfigController {

    private final AfsGreatWallFlowParamsService afsGreatWallFlowParamsService;

    @PostMapping("/listFlowParam")
    public IResponse<Page<FlowParamVo>> listFLowMapping(@RequestBody QueryCondition<FlowParamVo> condition) {
        return IResponse.success(afsGreatWallFlowParamsService.listFLowMapping(condition));
    }

    @PostMapping("/saveFlowParam")
    public IResponse<Boolean> saveFlowParam(@RequestBody FlowParamVo flowParamVo) {
        AfsGreatWallFlowParams afsGreatWallFlowParams = new AfsGreatWallFlowParams();
        BeanUtils.copyProperties(flowParamVo, afsGreatWallFlowParams);
        if (afsGreatWallFlowParams.getId() == null) {
            int count = afsGreatWallFlowParamsService.count(Wrappers.<AfsGreatWallFlowParams>lambdaQuery().eq(AfsGreatWallFlowParams::getGreatWallServiceId, afsGreatWallFlowParams.getGreatWallServiceId()).eq(AfsGreatWallFlowParams::getParamKey, afsGreatWallFlowParams.getParamKey()));
            Assert.isTrue(count == 0, "相同流程下的参数配置重复");
            afsGreatWallFlowParamsService.save(afsGreatWallFlowParams);
        } else {
            afsGreatWallFlowParamsService.updateById(afsGreatWallFlowParams);
        }
        return IResponse.success(Boolean.TRUE);
    }

    @PostMapping("/deleteFlowParam")
    public IResponse<Boolean> deleteFlowParam(@RequestBody FlowParamVo flowParamVo) {
        if (flowParamVo.getId() == null) {
            throw new AfsBaseException(CommonConstants.FAIL, "id为空不能执行删除");
        } else {
            afsGreatWallFlowParamsService.removeById(flowParamVo.getId());
        }
        return IResponse.success(Boolean.TRUE);
    }

}
